package com.zhupf.graph;


/**
 * @author zhupf
 * @date 2023年12月20日 16:50
 * @Description
 *
 *  208. 实现 Trie (前缀树)
 *
 */
public class Trie {

    public static void main(String[] args) {
        Trie trie = new Trie();
        trie.insert("apple");
        System.out.println(trie.search("apple"));
        System.out.println(trie.search("app"));
        System.out.println(trie.startsWith("app"));
        trie.insert("app");
        System.out.println(trie.search("app"));

    }

    public TrieNode trieNode;

    public Trie() {
        this.trieNode = new TrieNode();
    }

    public void insert(String word) {
        TrieNode ans = trieNode;
        for(int i = 0;i<word.length();i++){
            int c = word.charAt(i)-'a';
            if(ans.child[c] == null){
                ans.child[c] = new TrieNode();
            }
            ans = ans.child[c];
        }
        ans.isWord =true;
    }

    public boolean search(String word) {
        TrieNode ans = trieNode;
        for(int i = 0;i<word.length();i++){
            int c = word.charAt(i)-'a';
            if(ans.child[c] == null){
                return false;
            }
            ans = ans.child[c];
        }
        return ans.isWord;
    }

    public boolean startsWith(String prefix) {
        TrieNode ans = trieNode;
        for(int i = 0;i<prefix.length();i++){
            int c = prefix.charAt(i)-'a';
            if(ans.child[c] == null){
                return false;
            }
            ans = ans.child[c];
        }
        return true;
    }

    static class TrieNode{

        public boolean isWord;
        public TrieNode[] child;

        public TrieNode(){
            this.isWord = false;
            this.child = new TrieNode[26];
        }
    }

}
